import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit";
import { getSquareList } from "@src/service";

export interface PostListState {
  data: any;
  total: number;
  pageNumber: number;
  pageSize: number;
  loading: boolean; // 请求数据中
  error: string | null; // 是否错误
}

export type QueryParams = {
  refresh?: boolean,
}

const initialState: PostListState = {
  data: [],
  total: 0,
  pageNumber: 1,
  pageSize: 10,
  loading: false,
  error: null,
};


export const getPostList = createAsyncThunk<any, QueryParams>(
  "post/getPostList",
  async (params: QueryParams, { signal, rejectWithValue }) => {
    console.log(params, "接口需要的参数");
    try {
      let abort = () => { };
      signal.addEventListener("abort", () => {
        abort();
      });
      const response = await getSquareList({}, { abort });
      return response.data;
    } catch (error) {
      return rejectWithValue(error.response?.data || {});
    }
  }
);


export const PostListSlice = createSlice({
  name: "postList",
  initialState,
  reducers: {
  },
  extraReducers: {
    [getPostList.pending.type]: (state) => {
      state.loading = true;
    },
    [getPostList.fulfilled.type]: (state, action) => {
      console.log("postList");
      const { code, message, data: { items, total, page_size, page_num } } = action.payload;
      if (Object.is(code, 0)) {
        if (page_num === 1) {
          // 针对媒体资源对象合并处理
          items.map(item => {
            item.all_medias = item.media_detail.reduce((prev, next) => {
              return prev.concat(next.file_list_detail);
            }, []);
          });
          state.data = items;
        } else {
          state.data = state.data.concat(items);
        }
        state.loading = false;
        state.total = total;
        state.pageNumber = page_num;
        state.pageSize = page_size;
      } else {
        state.loading = false;
        state.error = message;
      }
    },
    [getPostList.rejected.type]: (state, action: PayloadAction<string | null>) => {
      state.loading = false;
      state.error = action.payload;
    }
  }
});


